package com.tony.pmp.server.controller;

import com.google.common.collect.Maps;
import com.tony.pmp.common.response.BaseResponse;
import com.tony.pmp.common.response.StatusCode;
import com.tony.pmp.common.utils.Constant;
import com.tony.pmp.model.entity.SysMenuEntity;
import com.tony.pmp.server.service.SysMenuService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: SysMenuController
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/21/20:16
 * @Description: 菜单接口
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
    * @Description: list 获取菜单列表
    * @Param: []
    * @return: java.util.List<com.tony.pmp.model.entity.SysMenuEntity>
    * @Author: 皮蛋布丁
    * @Date: 2021/7/21 20:43
    */
    @RequestMapping("/list")
    @RequiresPermissions(value = {"sys:menu:list"})
    public List<SysMenuEntity> list() {
        //region 第一种写法：mybaits-plus sericeimpl实现

        List<SysMenuEntity> list = sysMenuService.list();
        if (list != null && !list.isEmpty()) {
            list.stream().forEach(entity -> {
                //去除图标的父级菜单名称
                if (Constant.MenuType.BUTTON.getValue() == entity.getType()) {
                    SysMenuEntity menu = sysMenuService.getById(entity.getParentId());
                    entity.setParentName((menu != null && StringUtils.isNotBlank(menu.getName()))? menu.getName() : "");
                }
            });
        }
        return list;

        //endregion

        //region 第二种方式：自己写sql实现

//        return sysMenuService.queryAll();

        //endregion
    }

    /**
    * @Description: select 获取菜单树形层级列表数据
    * @Param: []
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/22 13:43
    */
    @RequestMapping("/select")
    public BaseResponse select(){
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            //获取数据
            List<SysMenuEntity> list = sysMenuService.queryNotButtonList();

            SysMenuEntity entity = new SysMenuEntity();
            entity.setMenuId(Constant.TOP_MENU_ID);
            entity.setName(Constant.TOP_MENU_NAME);
            entity.setParentId(-1L);
            entity.setOpen(true);
            list.add(entity);

            resMap.put("menuList",list);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    /**
    * @Description: save 新增菜单
    * @Param: [entity]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/22 16:00
    */
    @RequestMapping(value = "/save",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresPermissions(value = {"sys:menu:save"})
    public BaseResponse save(@RequestBody SysMenuEntity entity) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("新增菜单的数据为：{}",entity);
            String result =this.validateForm(entity);
            if (StringUtils.isNotBlank(result)) {
                return new BaseResponse(StatusCode.Fail.getCode(),result);
            }

            log.info("新增菜单结果为：{}",sysMenuService.save(entity));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: validateForm 校验参数是否正确
    * @Param: [menu]
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/7/22 15:42
    */
    private String validateForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            return "菜单名称不能为空！";
        }
        if (menu.getParentId() == null) {
            return "上级菜单不能为空！";
        }

      //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                return "菜单链接url不能为空！";
            }
        }

      //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();

        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() || menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                return "上级菜单只能为目录类型！";
            }
            return "";
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                return "上级菜单只能为菜单类型！";
            }
            return "";
        }
        return "";
    }

    /**
    * @Description: info 根据id获取菜单详情信息
    * @Param: [menuId]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/22 16:17
    */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions(value = {"sys:menu:info"})
    public BaseResponse info(@PathVariable Long menuId) {
        if (menuId == null || menuId <= 0) {
            return new BaseResponse(StatusCode.InvalidParams);
        }

        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            resMap.put("menu",sysMenuService.getById(menuId));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }

    /**
    * @Description: update 更新菜单数据
    * @Param: [entity]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/23 22:53
    */
    @RequestMapping(value = "/update",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresPermissions(value = {"sys:menu:update"})
    public BaseResponse update(@RequestBody SysMenuEntity entity) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("修改菜单的数据为：{}",entity);
            //校验参数是否正确
            String result = this.validateForm(entity);
            if (StringUtils.isNotBlank(result)) {
                return new BaseResponse(StatusCode.Fail.getCode(),result);
            }
            log.info("菜单更新的状态为：{}",sysMenuService.updateById(entity));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: delete 删除菜单
    * @Param: [menuId]
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/7/23 23:00
    */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @RequiresPermissions(value = {"sys:menu:delete"})
    public BaseResponse delete(Long menuId) {
        if (menuId == null || menuId <= 0) {
            return new BaseResponse((StatusCode.InvalidParams));
        }
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            log.info("删除菜单的id为：{}",menuId);
            SysMenuEntity entity = sysMenuService.getById(menuId);
            if (entity == null) {
                return new BaseResponse(StatusCode.InvalidParams);
            }
            //根据父级id获取子菜单
            List<SysMenuEntity> list = sysMenuService.queryByParentId(entity.getParentId());
            if (list != null && list.isEmpty()) {
                return new BaseResponse(StatusCode.MenuHasSubMenuListCanNotDelete);
            }
            log.info("删除的状态为：{}",sysMenuService.delete(menuId));
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }

    /**
    * @Description: nav 获取首页导航菜单列表
    * @Param: []
    * @return: com.tony.pmp.common.response.BaseResponse
    * @Author: 皮蛋布丁
    * @Date: 2021/8/1 13:17
    */
    @RequestMapping("/nav")
    public BaseResponse nav() {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        Map<String,Object> resMap = Maps.newHashMap();
        try {
            List<SysMenuEntity> list = sysMenuService.getUserMenuList(getUserId());
            resMap.put("menuList",list);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        response.setData(resMap);
        return response;
    }
































}
